<template>
  <div class="box">
    <el-form :model="form" label-width="135px">
      <h3>基本信息</h3>
      <!-- //基本信息表单部分 -->
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="借款名称：" required>
            <label>{{ form.name }}</label>
          </el-form-item>
          <el-form-item label="借款方：" required>
            <label>{{ form.userPhone }}</label>
          </el-form-item>
          <el-form-item label="年利率：" required>
            <label>{{ form.apr }}</label>
          </el-form-item>
          <el-form-item label="借款期限：" required>
            <label>{{ form.loanPeriod }}</label>
          </el-form-item>
          <el-form-item label="还款方式：" required>
            <label>{{ form.repayment }}</label>
          </el-form-item>
          <el-form-item label="资金用途：" required>
            <label>{{ form.useOfFunds }}</label>
          </el-form-item>
          <!-- <el-form-item label="利息管理费：" required>
            <label>{{ form. }}</label>
          </el-form-item> -->
          <!-- <el-form-item label="资金用途：" required>
            <label>{{ form.useOfFunds }}</label>
          </el-form-item> -->
        </el-col>

        <el-col :span="12">
          <el-form-item label="风险等级：" required>
            <label>{{ form.riskLevel }}</label>
          </el-form-item>
          <el-form-item label="借款总金额：" required>
            <label>{{ form.total }}</label>
          </el-form-item>
          <el-form-item label="起息方式：" required>
            <label>{{ form.interestWay }}</label>
          </el-form-item>
          <el-form-item label="借款管理费：" required>
            <label>{{ form.loanMgrInterestRate }}</label>
          </el-form-item>
          <el-form-item label="罚息利率：" required>
            <label>{{ form.overdue }}</label>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 担保信息 -->
      <h3>担保信息</h3>
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="是否担保：">
            <label>{{ form.guaranteed }}</label>
          </el-form-item>
          <el-form-item label="是否抵押：">
            <label>{{ form.mortgageType }}</label>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="担保机构：">
            <label>{{ form.guaranteeAgency }}</label>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 借款资料 -->
      <h3>借款资料</h3>
      <el-row>
        <el-col>
          <el-form-item label="借款资料：">
            <ImageList :imageList="form.loanInformation"></ImageList>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <h3>标的信息</h3>
    <el-form :model="addForm" :rules="rules" ref="addForm" label-width="135px">
      <!-- 标的信息 -->
      <el-row :gutter="40">
        <!-- 基本信息部分 -->
        <el-col :span="10">
          <el-form-item label="标名：" required="">
            <el-input
              v-model="form.name"
              placeholder="请输入标名"
              disabled
            ></el-input>
          </el-form-item>

          <el-form-item label="标的类型：" prop="typeId" required="">
            <el-row>
              <el-select
                v-model="addForm.typeId"
                clearable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in genre"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-row>
          </el-form-item>

          <el-form-item label="递增金额：" required="">
            <el-row>
              <el-select
                v-model="addForm.incrementalAmount"
                clearable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in increase"
                  :key="item.value"
                  :label="item.value"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-row>
          </el-form-item>

          <el-form-item label="投资计息方式：" required="">
            <el-radio-group v-model="addForm.investmentInterestCalWay">
              <el-radio v-for="item in way" :label="item.text" :key="item.text">
                {{ item.text }}
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="设置精选：" required="">
            <el-radio-group v-model="addForm.featured">
              <el-radio
                v-for="item in feat"
                :label="item.label"
                :key="item.label"
              >
                {{ item.text }}
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="募集时间：" required>
            <el-row :gutter="10">
              <el-col :span="9">
                <el-select
                  v-model="recruitmentTime"
                  clearable
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in raise"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="14">
                <el-input
                  v-model="timeInput"
                  type="text"
                  suffix="小时"
                  placeholder="请输入整数"
                  :disabled="(recruitmentTime == 1) ? false:true"
                >
                  <template slot="append">小时</template>
                </el-input>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="开售时间：" required="">
            <!-- <div class="block"> -->
            <el-date-picker
              v-model="addForm.saleTime"
              align="right"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
            <!-- </div> -->
          </el-form-item>
        </el-col>

        <el-col :span="10">
          <el-form-item label="标签：" prop="tag">
            <el-input
              v-model="addForm.tag"
              placeholder="请选择标签"
              @focus="tagDialogVisible = true"
              :readonly="true"
            ></el-input>
            <el-dialog
              title="标的标签"
              :visible.sync="tagDialogVisible"
              width="40%"
              center
            >
              <div>
                <el-checkbox-group v-model="checkTag">
                  <el-checkbox-button
                    v-for="tag in tags"
                    :label="tag"
                    :key="tag"
                    >{{ tag }}</el-checkbox-button
                  >
                </el-checkbox-group>
              </div>
              <span slot="footer" class="dialog-footer">
                <el-button @click="tagDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleCloseTag"
                  >确 定</el-button
                >
              </span>
            </el-dialog>
          </el-form-item>

          <el-form-item
            label="最低起投金额："
            prop="minInvestmentAmount"
            required
          >
            <el-input
              v-model="addForm.minInvestmentAmount"
              placeholder="请输入0-999999之间的整数"
              ><template slot="append">元</template>
            </el-input>
          </el-form-item>

          <el-form-item
            label="最大可投金额："
            prop="maxInvestmentAmount"
            required
          >
            <el-input
              v-model="addForm.maxInvestmentAmount"
              placeholder="大于最小可投且小于借款总额的正整数"
              ><template slot="append">元</template>
            </el-input>
          </el-form-item>

          <el-form-item label="上架渠道：" required="">
            <el-checkbox-group v-model="shelfChannel">
              <el-checkbox label="PC">PC</el-checkbox>
              <el-checkbox label="APP">APP</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="新手专享：" required="">
            <el-radio-group v-model="addForm.exclusiveForNovices">
              <el-radio
                v-for="item in clus"
                :label="item.label"
                :key="item.label"
              >
                {{ item.text }}
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="标的上架时间：" required="">
            <el-date-picker
              v-model="addForm.gmtCreated"
              align="right"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 富文本编辑-项目介绍 -->
      <p>项目介绍</p>
      <el-row >
        <div class="box3">
          <quill-editor
            v-model="addForm.projectIntroduction"
            ref="projectIntroduction"
            :options="editorOption"
            @change="onEditorChange($event)"
            @ready="onEditorReady($event)"
          >
          </quill-editor>
        </div>
      </el-row>

      <!--  -->
      <p>风控措施</p>
      <el-row>
        <div class="box4">
          <quill-editor
            v-model="addForm.riskControlMeasures"
            ref="riskControlMeasures"
            :options="editorOption"
            @change="onEditorChange($event)"
            @ready="onEditorReady($event)"
          >
          </quill-editor>
        </div>
      </el-row>
    </el-form>

    <el-row>
      <div class="across"></div>
      <div class="keystroke">
        <el-row>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button type="success" @click="handleReturn">返回</el-button>
        </el-row>
      </div>
    </el-row>
  </div>
</template>

<script>

import { getLoanById, getAllLoanType,shelfLoan} from "../../http/loan";
import ImageList from "../../components/loan/ImageList.vue";

export default {
  name: "LoanStsm",
  components: {
    ImageList,
  },
  watch: {
    timeInput() {
      let time = parseInt(this.timeInput);
      this.addForm.recruitmentTime = isNaN(time)
        ? 0
        : this.recruitmentTime * time;
    },
    recruitmentTime() {
      let time = parseInt(this.timeInput);
      this.addForm.recruitmentTime = isNaN(time)
        ? 0
        : this.recruitmentTime * time;
    },
    formData() {
      this.form = this.getInitRoleForm();
    },
    shelfChannel(newVal) {
      this.addForm.shelfChannel = newVal.join(",");
    },
  },
  data() {
    let minInvestmentAmount = (rule, value, callback) => {
      let num = parseInt(value);

      if (value === "") {
        callback(new Error("最低起投金额不能为空"));
      } else if (num < 0 || num > 999999) {
        callback(new Error("请输入正确的起投金额"));
      } else {
        callback();
      }
    };
    let maxInvestmentAmount = (rule, value, callback) => {
      let num = parseInt(value);

      if (value === "") {
        callback(new Error("最大可投金额不能为空"));
      } else if (num < 0 || num > 999999) {
        callback(new Error("请输入正确的起投金额"));
      } else {
        callback();
      }
    };
    return {
      // form: {
      //   apr: "",
      //   asd: "",
      //   interestWay: "",
      //   loanMgrInterestRate: "",
      //   loanPeriod: "",
      //   loanType: "",
      //   name: "",
      //   overdue: "",
      //   repayment: "",
      //   riskLevel: "",
      //   termType: "",
      //   total: "",
      //   useOfFunds: "",
      //   userPhone: "",
      //   guaranteeAgency: "",
      //   guaranteed: "",
      //   mortgageType: "",
      // },
      form: this.getInitRoleForm(),
      addForm: {
        typeId: "",
        tag: "",
        incrementalAmount: "100",
        investmentInterestCalWay: "成交日",
        featured: false,
        recruitmentTime:0,
        exclusiveForNovices: false,
        projectIntroduction: "",
        riskControlMeasures: "",
        shelfChannel: "PC,APP",
        gmtCreated: "",
        saleTime: "",
        minInvestmentAmount: "",
        maxInvestmentAmount: "",
      },
      rules: {
        minInvestmentAmount: [
          { validator: minInvestmentAmount, trigger: "blur" },
        ],
        maxInvestmentAmount: [
          { validator: maxInvestmentAmount, trigger: "blur" },
        ],
        typeId: [
          { required: true, message: "请选择选标的类型", trigger: "change" },
        ],
        tag: [
          { required: true, message: "请至少选一个标签", trigger: "change" },
        ],
        // recruitmentTime: [
        //   { validator: this.recruitmentTimeValidator, trigger: "blur" },
        // ],
      },
      formData: {},
      tags: [
        "高收益",
        "低风险",
        "官方标",
        "红包可用",
        "仅限新用户",
        "限时抢投",
      ],
      tagDialogVisible: false,
      checkTag: [],
      genre: [],
      increase: [
        {
          value: "100",
        },
        {
          value: "200",
        },
        {
          value: "500",
        },
        {
          value: "1000",
        },
      ],
      way: [
        {
          text: "成交日",
        },
        {
          text: "T+1",
        },
        {
          text: "T+2",
        },
        {
          text: "成立计息",
        },
      ],
      feat: [
        {
          text: "否",
          label: false,
        },
        {
          text: "是",
          label: true,
        },
      ],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      saleTime: "",
      raise: [
        {
          label: "满标为止",
          value: 0,
        },
        {
          label: "设置时间",
          value: 1,
        },
      ],
      recruitmentTime: 0,
      timeInput: "",
      clus: [
        {
          text: "否",
          label: false,
        },
        {
          text: "是",
          label: true,
        },
      ],
      projectIntroduction: "",
      riskControlMeasures: "",
      quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
      serverUrl: "", // 这里写你要上传的图片服务器地址
      header: { token: sessionStorage.token }, // 有的图片服务器要求请求头需要有token之类的参数，写在这里
      detailContent: "", // 富文本内容
      editorOption: {}, // 富文本编辑器配置
      shelfChannel: ["PC", "APP"],
    };
  },

  methods: {
    // 上传图片前
    beforeUpload(res, file) {
      console.log(res, file);
    },
    // 上传图片成功
    uploadSuccess(res, file) {
      console.log(res, file);
    },
    // 上传图片失败
    uploadError(res, file) {
      console.log(res, file);
    },

    onEditorChange() {
      console.log(this.projectIntroduction);
    },

    onEditorReady() {},

    handleCloseTag() {
      this.addForm.tag = this.checkTag.join(",");
      this.tagDialogVisible = false;
    },
    handleReturn() {
            this.$router.push("/loan/loantarget")
    },
    handleSubmit() {
      this.$refs.addForm.validate((valid) => {
        if(valid){
          console.log("addForm",this.addForm)
          let temp = this._.cloneDeep(this.addForm);
          temp.gmtCreated = temp.gmtCreated.getTime();
          temp.saleTime = temp.saleTime.getTime();
          shelfLoan(this.$route.params.id,temp).then((res) => {
          console.log("getLoanById:", res);
          if (res.data.code == 20000) {
            console.log(res);
            this.$message.success("提交成功！");
            this.$router.push("/loan/loantarget")
          } else {
            this.$message.error("提交失败！");
          }
        })
        .catch((err) => {
          console.err(err);
          this.$message.error("提交失败！");
        });
        }
      });
      console.log(this.addForm);
    },
    // recruitmentTimeValidator(rule, value, callback){
    //   console.log("recruitmentTimeValidator", value)
    //   callback();
    // }
  },
  beforeMount() {
    let id = this.$route.params.id;
    if (!this._.isUndefined(id)) {
      getLoanById(id)
        .then((res) => {
          console.log("getLoanById:", res);
          if (res.data.code == 20000) {
            console.log(res);
            this.formData = res.data.data.info;
          } else {
            this.$message.error("请求标的详细信息出错！");
          }
        })
        .catch((err) => {
          console.err(err);
          this.$message.error("请求标的详细信息出错！");
        });
    }
    getAllLoanType()
      .then((res) => {
        console.log("getLoanType:", res);
        if (res.data.code == 20000) {
          console.log(res);
          this.genre = res.data.data.info
            .filter((item) => !item.status)
            .map((item) => ({ name: item.name, id: item.id }));
        } else {
          this.$message.error("请求标的类型出错！");
        }
      })
      .catch((err) => {
        console.err(err);
        this.$message.error("请求标的类型出错！");
      });
  },
  beforeCreate() {
    const defaultData = {
      apr: "", //年利率
      asd: "", //还款方式
      interestWay: "",
      loanMgrInterestRate: "", //借款管理月利率
      loanPeriod: "", //借款期限 （天）
      loanType: "", //借款类型
      name: "", //标名
      overdue: "", //逾期罚息利率
      repayment: "", //还款方式
      riskLevel: "", //风险等级
      termType: "", //期限类型（天）
      total: "", //借款金额
      useOfFunds: "", //资金用途
      userPhone: "", //借款人联系方式
      guaranteeAgency: "", //担保机构
      guaranteed: "", //是否担保
      mortgageType: "", //是否抵押
    };

    this.getInitRoleForm = function () {
      if (this._.isEmpty(this.formData)) return defaultData;
      let obj = {},
        formCopy = this._.cloneDeep(this.formData);
      for (let key in defaultData) {
        obj[key] = formCopy[key];
      }
      obj.guaranteed = formCopy.guarantee.guaranteed ? "是" : "否";
      obj.guaranteeAgency = formCopy.guarantee.guaranteeAgency;
      obj.mortgageType = formCopy.guarantee.mortgageType ? "是" : "否";
      obj.loanInformation = formCopy.loanInformation.split(",");
      return obj;
    };
  },
};
</script>

<style scoped>
.box {
  width: 91%;
  min-width: 1100px;
  margin-top: 80px;
  margin-left: 90px;
}
.quill-editor {
  height: 150px;
  margin-top: 20px;
}
.box3 {
  width: 1100px;
  height: 250px;
}
.box4 {
  width: 1100px;
  height: 250px;
}
.keystroke {
      width: 260px;
      height: 15px;
      margin-top: 30px; 
      margin-bottom: 100px;
      margin-left:auto;
      margin-right:auto;
    }
.across {
  border-top: 1px solid #dee1e6;
  width: 93%;
}
</style>